<template>
  <div class="wrapper">
    <div
      style="
        height: 60px;
        line-height: 60px;
        font-size: 20px;
        padding-left: 50px;
        color: saddlebrown;
        background-color: rgba(0, 0, 0, 0.2);
      "
    >
      企业员工信息管理系统
    </div>
    <div
      style="
        margin: 150px auto;
        background-color: saddlebrown;
        width: 350px;
        height: 300px;
        padding: 20px;
        border-radius: 10px;
      "
    >
      <div style="margin: 20px 0; text-align: center; font-size: 24px">
        <b>登 录</b>
      </div>
      <el-form :model="user" :rules="rules" ref="userForm">
        <el-form-item prop="username">
          <el-input
            size="medium"
            prefix-icon="el-icon-user"
            v-model="user.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            size="medium"
            prefix-icon="el-icon-lock"
            show-password
            v-model="user.password"
          ></el-input>
        </el-form-item>

        <el-form-item style="margin: 10px 0; text-align: right">
          <el-button
            type="warning"
            size="small"
            autocomplete="off"
            @click="$router.push('/register')"
            >前往注册</el-button
          >
          <el-button
            type="primary"
            size="small"
            autocomplete="off"
            @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item style="margin: 10px 0; text-align: right">
          <el-button
            type="text"
            size="mid"
            autocomplete="off"
            @click="handlePass"
            >找回密码</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="找回密码" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="100px" size="small">
        <el-form-item label="用户名">
          <el-input v-model="pass.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="pass.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="passwordBack">重置密码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { resetRouter, setRoutes } from "@/router";
import Identify from "@/components/Identify";
import { BMPGL } from "@/bmpgl.js";
export default {
  name: "Login",
  data() {
    return {
      user: {},
      pass: {},
      code: "",
      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      latitude: null,
      longitude: null,
      error: null,
      address: "",
      ak: "", // 百度地图秘钥填写自己的ak
    };
  },
  components: { Identify },
  mounted() {
    // 重置路由
    resetRouter();
  },
  methods: {
    login() {
      this.$refs["userForm"].validate((valid) => {
        if (valid) {
          // 表单校验合法
          this.request.post("/user/login", this.user).then((res) => {
            if (res.code === "200") {
              this.getLocation();
              this.getBMapLocation()
              localStorage.setItem("user", JSON.stringify(res.data)); // 存储用户信息到浏览器
              localStorage.setItem("menus", JSON.stringify(res.data.menus)); // 存储用户关联的菜单到浏览器
              // 动态设置当前用户的路由
              setRoutes();
              this.$router.push("/");
              this.$message.success("登录成功");
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    handlePass() {
      this.dialogFormVisible = true;
      this.pass = {};
    },
    passwordBack() {
      this.request.put("/user/reset", this.pass).then((res) => {
        if (res.code === "200") {
          this.$message.success("重置密码成功，新密码为：123，请尽快修改密码");
          this.dialogFormVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    getBMapLocation() {
      BMPGL(this.ak)
        .then((BMapGL) => {
          var geolocation = new BMapGL.Geolocation();
          geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              let map = new BMapGL.Map("container");
              map.centerAndZoom(r.point, 15); //r.point就是当前定位坐标，设置为地图中心点
              var mk = new BMapGL.Marker(r.point);
              map.addOverlay(mk); //添加标点
              map.panTo(r.point);
              console.log("您的位置：" + r.point.lng + "," + r.point.lat);
              this.address = `${r.address.province} ${r.address.city} ${r.address.district} ${r.address.street} ${r.address.street_number}`; //中文 详细地址
              localStorage.setItem("address", this.address);
            } else {
              alert("failed" + this.getStatus());
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getLocation() {
      // 获取定位

      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;
            this.error = null;
            console.log(this.latitude, this.longitude);
            localStorage.setItem("latitude", this.latitude);
            localStorage.setItem("longitude", this.longitude);
          },
          (error) => {
            this.error = error.message;
            this.latitude = null;
            this.longitude = null;
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0,
          }
        );
      } else {
        this.error = "Geolocation is not supported by your browser";
      }
    },
  },
};
</script>

<style>
.wrapper {
  height: 100vh;
  background-image: url("https://tse2-mm.cn.bing.net/th/id/OIP-C.njT10SItyfDNC3k4_4kW9AHaEK?rs=1&pid=ImgDetMain");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
</style>
